package com.cet.programmercarl.algorithmperformancanalysis.二叉树.左叶子之和;

/**
 * @program: algorithm
 * @description: 二叉树左叶子之和
 * @author: 陈恩涛
 * @create: 2022-07-20 21:25
 **/
public class LC404 {

    public static void main(String[] args) {
        final TreeNode root = new TreeNode(3, new TreeNode(9), new TreeNode(20, new TreeNode(15), new TreeNode(7)));
        System.out.println(new LC404().sumOfLeftLeaves(root));
        System.out.println(new LC404().sumOfLeftLeaves2(root));
    }

    public int sumOfLeftLeaves2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        final int leftLeftLeavesSum = sumOfLeftLeaves(root.left);
        final int rightLeftLeavesSum = sumOfLeftLeaves(root.right);
        int midValue = 0;
        if (root.left != null && root.left.left == null && root.left.right == null) {
            midValue += root.left.val;
        }
        return leftLeftLeavesSum + midValue + rightLeftLeavesSum;
    }

    public int sumOfLeftLeaves(TreeNode root) {
        postorderTraversal(root);
        return sum;
    }

    int sum = 0;

    private void postorderTraversal(TreeNode root) {
        if (root == null) {
            return;
        }
        if (isLeftLeafParent(root)) {
            sum += root.left.val;
        }
        postorderTraversal(root.left);
        postorderTraversal(root.right);

    }

    private boolean isLeftLeafParent(TreeNode node) {
        return node.left != null && node.left.left == null && node.left.right == null;
    }
}
